package com.company;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

public  class ReentrantLockList {
    //线程不安全的list
    private static ArrayList<String> array = new ArrayList<String>();
    //独占锁
    private static volatile ReentrantLock lock = new ReentrantLock();
    //添加元素
    public static void add(String e) {
        lock.lock();
        try {
            array.add(e);
        } finally {
            lock.unlock();
        }
    }

    //删除元素
    public static void remove(String e) {
        lock.lock();
        try {
            array.remove(e);
        } finally {
            lock.unlock();
        }
    }

    //获取数据
    public static String get(int index) {
        lock.lock();
        try {
            return array.get(index);

        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            while ( true ){
                add("xiaobai");
            }
        }).start();
        new Thread(() -> {
            while ( true ){
                get(0);
            }
        }).start();
        new Thread(() -> {
            while ( true ){
                remove("xiaobai");
            }
        }).start();
    }
}